package com.imstlife.vending.utils;

import android.app.Activity;
import android.content.Context;

import java.util.Stack;

/**
 * Created by lihaifeng on 16/10/27.
 */
public class AppManager {

    /** app栈  */
    private Stack<Activity> activityStack;

    /** AppManager 内部 静态 实例 供单时使用*/
    private static AppManager instance;

    /**
     * 单例模式
     */
    public static AppManager getInstance( ){
        if(instance==null){
            instance=new AppManager();
        }
        return instance;
    }
    /**
     * 添加activity到栈
     * @param activity
     */
    public void  addActivity (Activity activity){
        if(activityStack==null){
            activityStack = new Stack<Activity>();
        }
        activityStack.add(activity);
    }

    /**
     * 获取当前Activity  最后一个压入栈的
     * @return
     */
    public Activity currentActivity(){
        return activityStack.lastElement();
    }

    /**
     * 结束当前activity
     */
    public void finishActivity(){
        finishActivity(activityStack.lastElement());
    }

    /**
     * 删除指定activity
     * @param activity
     */
    public void finishActivity(Activity activity) {

        if (activity != null && !activity.isFinishing()) {
            activityStack.remove(activity);
            activity.finish();
            activity = null;
        }

    }

    /**
     * 删除指定类名的Activity
     * @param cls
     */
    public void finishActivity(Class<?> cls){

        for(Activity activity:activityStack){
            if(activity.getClass().equals(cls)){
                finishActivity(activity);
            }
        }
    }

    /**
     * 关闭所以activity
     */
    public void finishAllActivity(){
        for(int i = 0 ; i < activityStack.size();i++){
            if(null!=activityStack.get(i)){
                finishActivity(activityStack.get(i));
            }
        }
        activityStack.clear();

    }

    /**
     * 获取指定Activity
     */
    public Activity getActivity(Class<?> cls){
        if(activityStack!=null){
            for(Activity activity:activityStack){
                if(activity.getClass().equals(cls)){
                    return activity;
                }
            }
        }
        return null;
    }


    /**
     * 退出应用程序
     * @param context
     */
    public void AppExit(Context context){
        try {

            finishAllActivity();
            android.os.Process.killProcess(android.os.Process.myPid());
            System.exit(0);
        }catch (Exception e){
            e.printStackTrace();
        }

    }


}
